package com.itheima.easy.handler.wechat;

import com.alibaba.fastjson.JSONObject;
import com.itheima.easy.client.Config;
import com.itheima.easy.client.Factory;
import com.itheima.easy.client.response.PagePayResponse;
import com.itheima.easy.constant.SuperConstant;
import com.itheima.easy.constant.TradingConstant;
import com.itheima.easy.entity.Trading;
import com.itheima.easy.enums.TradingEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.handler.PagePayHandler;
import com.itheima.easy.utils.BeanConv;
import com.itheima.easy.utils.EmptyUtil;
import com.itheima.easy.utils.ExceptionsUtil;
import com.itheima.easy.utils.ResponseChecker;
import com.itheima.easy.vo.TradingVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ClassName WechatPagePayHandler.java
 * @Description PC网页支付处理实现
 */
@Slf4j
@Component
public class WechatPagePayHandler extends WechatCommonPayHandler implements PagePayHandler {

    @Override
    public TradingVo pageTrading(TradingVo tradingVo){
        //1、交易前置处理：检测交易单参数
        Boolean flag = beforePayHandler.checkeCreateTrading(tradingVo);
        if (!flag){
            throw new ProjectException(TradingEnum.PAYING_TRADING_FAIL);
        }
        //2、交易前置处理：幂等性处理
        beforePayHandler.idempotentCreateTrading(tradingVo);
        //3、获得微信客户端
        Config config = wechatPayConfig.config();
        //4、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new RuntimeException("微信支付配置为空！");
        }
        //5、指定配置文件
        Factory factory = new Factory();
        factory.setOptions(config);
        try {
            //6、调用接口
            PagePayResponse pagePayResponse = factory.Page().pay(
                String.valueOf(tradingVo.getTradingOrderNo()),
                String.valueOf(tradingVo.getTradingAmount()),
                tradingVo.getMemo(),
                tradingVo.getOpenId());
            //7、受理结果【只表示请求是否成功，而不是支付是否成功】
            boolean success = ResponseChecker.success(pagePayResponse);
            if (success&&!EmptyUtil.isNullOrEmpty(pagePayResponse.getPrepayId())){
                tradingVo.setIsRefund(SuperConstant.NO);
                tradingVo.setEnterpriseId(Long.valueOf(config.getMchId()));
                tradingVo.setPlaceOrderCode(pagePayResponse.getCode());
                tradingVo.setPlaceOrderMsg(pagePayResponse.getMessage());
                tradingVo.setPlaceOrderJson(pagePayResponse.getPrepayId());
                tradingVo.setTradingState(TradingConstant.TRADE_WAIT_BUYER_PAY_1);
                Trading trading = BeanConv.toBean(tradingVo, Trading.class);
                tradingService.saveOrUpdate(trading);
            }else {
                log.error("网关：微信Page支付preCreate：{},结果：{}", tradingVo.getTradingOrderNo(),
                        JSONObject.toJSONString(pagePayResponse));
                throw new RuntimeException("网关：微信Page支付preCreate发生异常!");
            }
        } catch (Exception e) {
            log.error("微信用户扫商家统一下单创建失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new RuntimeException("微信商家扫用户统一下单创建失败！");
        }
        return tradingVo;
    }

}
